package GameServer;

import Library.Game.*;
import Library.Game.IGameInfo;
import java.io.IOException;
import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;

/**
 *
 */
public class GameServerManager extends javax.swing.JFrame
{
    /**
     *
     */
    protected GameServer m_gs;
    /**
     *
     */
    protected List<IGame> m_games;

    /**
     * Creates new form Gameservertester
     * @throws RemoteException 
     * @throws SQLException 
     * @throws IOException
     */
    public GameServerManager() throws RemoteException, SQLException, IOException
    {
        initComponents();
        m_gs = new GameServer();
        if (m_gs.startServer())
	    txtOutput.append("GameServer Started on " + m_gs.getPort());
	else
	    txtOutput.append("GameServer Failed to start on " + m_gs.getPort());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGames = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtOutput = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstGamelist = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        lblSelectedGame = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstUserlist = new javax.swing.JList();
        btnGameUsers = new javax.swing.JButton();
        btnRemoveGame = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Gameserver Manager");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        btnGames.setText("Refresh Games");
        btnGames.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGamesActionPerformed(evt);
            }
        });

        jLabel1.setText("Game List");

        txtOutput.setColumns(20);
        txtOutput.setRows(5);
        jScrollPane3.setViewportView(txtOutput);

        jLabel3.setText("Output");

        lstGamelist.setModel(new DefaultListModel());
        lstGamelist.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstGamelistValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(lstGamelist);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Game Information"));

        lblSelectedGame.setText("(no game selected)");

        jLabel2.setText("Ingame Players");

        lstUserlist.setModel(new DefaultListModel());
        jScrollPane2.setViewportView(lstUserlist);

        btnGameUsers.setText("Refresh Player List");
        btnGameUsers.setEnabled(false);
        btnGameUsers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGameUsersActionPerformed(evt);
            }
        });

        btnRemoveGame.setText("Remove Game");
        btnRemoveGame.setEnabled(false);
        btnRemoveGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveGameActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
                            .addComponent(lblSelectedGame)
                            .addComponent(jLabel2)
                            .addComponent(btnGameUsers, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnRemoveGame, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                        .addGap(159, 159, 159))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lblSelectedGame)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnGameUsers)
                .addGap(18, 18, 18)
                .addComponent(btnRemoveGame)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(btnGames, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnGames))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGamesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGamesActionPerformed
        DefaultListModel mdl = (DefaultListModel)lstGamelist.getModel();
        mdl.clear();
        try
        {
            m_games = m_gs.getGames();
            txtOutput.setText("Retrieving GameList...\r\n");
            lstGamelist.removeAll();
            Iterator<IGame> it = m_games.iterator();
            if (!it.hasNext())
                txtOutput.append("No active games available.\r\n");
            else 
            {
                while(it.hasNext())
                {
                    mdl.addElement(it.next().getName());
                }
            }
        }
        catch (RemoteException ex)
        {
            ex.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnGamesActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (m_gs != null)
        {
            try
            {
                m_gs.dispose();
                m_gs = null;
            }
            catch (NoSuchObjectException ex)
            {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_formWindowClosing

    private void btnGameUsersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGameUsersActionPerformed
        
        DefaultListModel mdl = (DefaultListModel)lstUserlist.getModel();
        mdl.clear();
        int index = lstGamelist.getSelectedIndex();
        try
        {
            IGameInfo info = m_gs.findGame(lstGamelist.getSelectedValue().toString());
            if (info == null)
                txtOutput.setText("Game doesn't exist anymore");
            else
            {
                IGame findGame = m_gs.findGame(info);
                if (findGame == null)
                    txtOutput.setText("Game doesn't exist anymore");

                List playerlist = findGame.getPlayers();
                Iterator<IPlayer> it = playerlist.iterator();
                while(it.hasNext())
                {
                    mdl.addElement(it.next().getName());
                }   
            }
            lstGamelist.setSelectedIndex(index);
        }
        catch (RemoteException ex)
        {
            ex.printStackTrace();
            txtOutput.setText(ex.getMessage() + " --> cannot receive players from game!\r\n");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            txtOutput.setText(ex.getMessage() + " --> cannot receive players from game!\r\n");
        }
    }//GEN-LAST:event_btnGameUsersActionPerformed

    
    private void btnRemoveGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveGameActionPerformed

        try
        {
            IGameInfo info = m_gs.findGame(lstGamelist.getSelectedValue().toString());
            if (info == null)
                txtOutput.setText("Game doesn't exist anymore");
            else
            {
                IGame findGame = m_gs.findGame(info);
                if (findGame == null)
                    txtOutput.setText("Game doesn't exist anymore");
                else
                {
                    m_gs.closeGame(findGame);
                    txtOutput.setText("game " +  findGame.getName() +  " removed.\r\n");
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            txtOutput.setText(ex.getMessage() + " --> cannot remove game!\r\n");
        }
    }//GEN-LAST:event_btnRemoveGameActionPerformed

    private void lstGamelistValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstGamelistValueChanged
        
        if (lstGamelist.getSelectedIndex() == -1)
        {
            lblSelectedGame.setText("(no game selected)");
            ((DefaultListModel)lstUserlist.getModel()).clear();
            btnRemoveGame.setEnabled(false);
            btnGameUsers.setEnabled(false);
        }
        else
        {
            lblSelectedGame.setText(lstGamelist.getSelectedValue().toString());
            btnGameUsersActionPerformed(new java.awt.event.ActionEvent(this, 0, btnGameUsers.getText()));
            btnRemoveGame.setEnabled(true);
            btnGameUsers.setEnabled(true);
        }
    }//GEN-LAST:event_lstGamelistValueChanged

    /**
    * @param args the command line arguments
    */
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGameUsers;
    private javax.swing.JButton btnGames;
    private javax.swing.JButton btnRemoveGame;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblSelectedGame;
    private javax.swing.JList lstGamelist;
    private javax.swing.JList lstUserlist;
    private javax.swing.JTextArea txtOutput;
    // End of variables declaration//GEN-END:variables

}
